#Copyright 2009-2010 by Ward, David J ( pymethius@ominian.net )
import logging
log = logging.getLogger(__name__)
import StringIO, traceback

from webmud.handlers import base

from twisted.internet import defer
import twisted.python.failure

import sys
class Konsole(base.Base):
    """
        Hybrid self-directing class that handles the actual login work
    """
    def initialize(self):        
        self.scope = {"self":self}
        
    def bootstrap(self):
        self.makeRequest("loader", "konsole")
        #TODO , I don't think this is ever called :(
    
    def _compile(self, rawcode):
        """
            Allow exceptions like syntax error to ascend out of here
        """
        return compile(rawcode, '<string>','exec')
        
        
    def process(self, id, rawCode):
        """
            Expects a single param value of string that is some arbitrary type of code to be evaluated.
            It goes without saying that this entire handler should NEVER be granted to anyone but the SuperAdmin
        """
        #TODO - A better pattern must be found to resolve the disconnect from the old protocol and new protocol instance
        self.scope['self'] = self
        
        logging.debug("was called with `%s`" % rawCode)
        buffer = StringIO.StringIO()
        buffer.write(">> %s\n" % rawCode)
        
        try:
            compiled = self._compile(rawCode)
        except Exception,e:
            buffer.write("Compilation error %s" % e)
            self.sendResponse(buffer.getvalue() , id)
            return        
            
    
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        try:            
            sys.stdout  = buffer            
            sys.stderr  = buffer             
            exec compiled in self.scope
        except Exception, e:
            buffer.write(traceback.print_exc())
            buffer.write("Exception! %s" % e)            
        finally:            
            sys.stdout, sys.stderr = self.stdout, self.stderr            
            result = buffer.getvalue()            
            self.sendResponse(result, id)
    
    #Alias because the JS client was already wired to konsole.run :(
    run = process
    
    
    def _listRoutes(self):
        """
            Konsole user helper method to tell the user their currently available handlers
        """
        for key, handler in self.user.handleRequest.routes.items():
            print key, handler
        